<?php
/************************FoxPHP威客系统************************/
/*                                                            */
/*  FoxPHP.Com (C)2006-2016 FoxPHP Inc.                       */
/*  This is NOT a freeware, use is subject to license terms   */
/*  FoxPHP威客系统是商业软件,使用于商业用途请购买授权         */
/*  V3.0 2016.3                                               */
/*  foxphp@aliyun.com                                         */
/*  http://www.foxphp.com                                     */
/*                                                            */
/**************************************************************/


namespace Consume\Model;
use Think\Model;
use \Org\Util\String;

class ConsumeModel extends Model {
	
	public $payinuid=1; //默认空UID 默认用户ID 1 
	
	public function __initialize(){ 
        
    }  
	
	function Callback(){
		return $this->callback;
	}
	
	//消费记录编号
	function GetOrderNumber($substr=4){	
	   $timearr=@gettimeofday();
	   return @date('YmdHis',$timearr['sec']).intval(substr($timearr['usec'],0,$substr));
	}
	
	//检查订单是否以存在
	function IsConsume($id=0){
		$id=intval($id);
		$consume=$this->token(false)->where(" dataid=$id ")->field('id,dataid')->find();
		if(!empty($consume['dataid'])){
			return $consume['id'];
		}
		return false;
	}
	
	//增加用户金额
	function AddUserMoney($uid=0,$username=null,$money=0,$subject=null){
		$uid=intval($uid);
		$money=intval($money);
		$subject=!empty($subject) ? $subject : $username.'用户增加金额'.$money.'元';
		if($uid && $money){
			
			$post=array(
				'subject'=>$subject,
				'amount' =>$money*100,
				'payin_uid'=>$uid,
				'payin_username'=>$username,
			);

			if($cid=$this->AddConsume($post)){
				$this->SuccessConsume($cid);
			}
		}
	}
	
	//减少用户金额
	function ReduceUserMoney($uid=0,$username=null,$money=0,$subject=null){
		$uid=intval($uid);
		$money=intval($money);
		$subject=!empty($subject) ? $subject : $username.'用户减少金额'.$money.'元';
		if($uid && $money){
			
			$post=array(
				'subject'=>$subject,
				'amount' =>$money*100,
				'payout_uid'=>$uid,
				'payout_username'=>$username,
			);

			if($cid=$this->AddConsume($post)){
				$this->SuccessConsume($cid);
			}
		}
	}
	
	//任务支付托管
	function PayTask($id=0,$money=0){
		$id=intval($id);
		$money=intval($money);
		if(!$money && !$id){
			$this->error='支付金额为空!';
			return false;
		}
		
		$cid=$this->IsConsume($id);
		
		if(!$cid){
		
			$post=array(
				'subject'=>$id.'号任务支付托管',
				'dataid' =>$id,
				'amount' =>$money*100,
				'payout_uid'=>$this->uid,
				'payout_username'=>$this->username,
			);

			$cid=$this->AddConsume($post);
		}
		
		if($cid){
			//支付
			if(!$this->SuccessConsume($cid)){
				$this->error=$this->getError();
				return false;
			}
			
			return $cid;
		}
		
		$this->error=$this->getError();
		return false;
	}
	
	//检查用户金额 单位分
	function CheckUserMoney($uid=0,$money=0){
		$money=intval($money);
		if($uid>0 && $money>0){
			M('Member')->startTrans();
			$member= M('Member')->token(false)->lock(true)->where(" uid=$uid ")->field('uid,money,moneyin,moneyout')->find();
			if($member['money']>=$money){
				M('Member')->commit();
				return true;
			}
			M('Member')->commit();
			return false;
		}else{
			return false;
		}
	}
	//添加消费记录
	function AddConsume($post=array()){
			
		//关联data表id
		$post['dataid']=intval($post['dataid']);

		$payinname=C('paysitename');
		
		$_POST['subject']=$post['subject'];
		$_POST['bankcard']=$post['bankcard'];
		
		//订单名称
		$post['subject']=String::msubstr(I('post.subject'),0,50,C('S_CHARSET'),false);

		
		//收入用户UID
		$post['payin_uid']=intval($post['payin_uid']) ? intval($post['payin_uid']) : $this->payinuid;
		
		//收入用户名
		$post['payin_username']=$post['payin_username'] ? $post['payin_username'] : $payinname;
		
		//收入后金额
		$post['payin_money']=floatval($post['payin_money']);
		
		//付款用户UID	
		$post['payout_uid']=intval($post['payout_uid']) ? intval($post['payout_uid']) : $this->payinuid;
		
		//付款用户名
		$post['payout_username']=$post['payout_username'] ? $post['payout_username'] : $payinname;
		
		//付款后金额
		$post['payout_money']=floatval($post['payout_money']);

		$post['paytype']= $post['paytype'] ? $post['paytype'] : 1;
		
		if(empty($post['serial'])){
			$post['serial']=$this->GetOrderNumber();
		}
		
		$post['process']= $post['process'] ? intval($post['process']) : 1;

		$post['fee']=floatval($post['fee']);
		
		//银行卡
		$post['bankcard']=String::msubstr(I('post.bankcard'),0,50,C('S_CHARSET'),false);
		
		//退款金额
		$post['refundmoney']=floatval($post['refundmoney']);
		
		//手动操作订单,操作员UID
		$post['operator']=intval($post['operator']);	
		
		//推广员UID
		$post['unionuid']=intval($post['unionuid']);	
		
		//创建时间, 最新操作时间 , 完成时间
		$post['dateline']=$post['newtime']=$post['endtime']=NowTime();

		$post['amount']=floatval($post['amount']);		
		
		$this->startTrans();
		$payoutuid=$post['payout_uid'];
		M('Member')->startTrans();
		$member= M('Member')->token(false)->lock(true)->where(" uid=$payoutuid ")->field('uid,money,moneyin,moneyout')->find();
	
		if(empty($member['uid'])){
			$this->error='用户不存在!';
			return false;
		}

		//检查用户金额
		if($member['money']<$post['amount']){
			$this->error='UID'.$member['uid'].',您的可用余额为'.($member['money']/100).'元,不足!'.($post['amount']/100).'元,请充值再操作！';
			return false;
		}
		
		if($this->token(false)->lock(true)->create($post)){
			if($id=$this->token(false)->lock(true)->add()){
				M('Member')->commit();
				$this->commit();
				return $id;
			}else{
				$this->rollback();
			}
		}else{
			$this->rollback();
		}

		$this->commit();
		$this->error=$this->getError();
		return false;
	}
	
	//设置成功订单
	public function SuccessConsume($id=0){
		$id=intval($id);
		if(!$id){
			$this->error='订单不存在!';
			return false;
		}
		
		$post['process']=5;
		
		//最新操作时间 , 完成时间
		$post['newtime']=$post['endtime']=NowTime();
		
		$post['autopay']=$post['autopaytime']=$post['autocommand']=0;
		
		$this->startTrans();
		
		$consume= $this->token(false)->lock(true)->where(" id=$id ")->find();
		
		if(!empty($consume['id']) && intval($consume['process'])>=5){
			$this->rollback();
			$this->commit();
			$this->error='订单重复操作!';
			return false;
		}elseif(!empty($consume['id']) && intval($consume['process'])<5){

			$this->token(false)->lock(true)->where(" id=$id ")->save($post);

			if($consume['refundmoney']>=$consume['amount']){
				$amount=($consume['amount']+$consume['fee']) - $consume['refundmoney']; 
			}else{
				$amount=$consume['amount']-$consume['refundmoney']; 
			}
			
			if(!$amount){
				//关闭订单
				$this->CloseConsume($id);
				$this->commit();
				return true;
			}

			//付款人
			$payoutuid=intval($consume['payout_uid']);
			$payoutmember= M('Member')->token(false)->lock(true)->where(" uid=$payoutuid")->field('uid,money,moneyin,moneyout')->find();
			
			//收入人
			$payinuid=intval($consume['payin_uid']);
			$payinmember= M('Member')->token(false)->lock(true)->where(" uid=$payinuid")->field('uid,money,moneyin,moneyout')->find();
				
			if($payoutmember['money']>=$amount && !empty($payinmember['uid'])){
				$payoutmoney=$payoutmember['money']-$amount;
				M('Member')->token(false)->lock(true)->where(" uid=$payoutuid ")->save(array('money'=>$payoutmoney,'moneyout'=>$payoutmember['moneyout']+$amount));

				$payinmoney=$payinmember['money']+$amount;
				M('Member')->token(false)->lock(true)->where(" uid=$payinuid ")->save(array('money'=>$payinmoney,'moneyin'=>$payinmember['moneyin']+$amount));
				
				$this->token(false)->lock(true)->where(" id=$id ")->save(array('payout_money'=>$payoutmoney,'payin_money'=>$payinmoney));
	
				$this->commit();
				return true;
			}else{
				$this->rollback();
				$this->commit();
				$this->error='支付金额不足'.($amount/100).'元';
				return false;
			}
			
		}else{
			$this->rollback();
		}
		
		$this->error='订单不存在!';
		$this->commit();
		return false;
		
	}
	
	//关闭订单
	public function CloseConsume($id=0){
		$this->startTrans();
		$this->token(false)->lock(true)->where(" id=$id ")->save(array('process'=>6));
		$this->commit();
		return true;
	}
	
	//任务手续费
	function GetTaskFee($uid=0,$money=0,$feetype='taskfee'){
		$uid=intval($uid);
		$member= M('Member')->token(false)->where(" uid=$uid ")->field('usergroup')->find();
		if($money && !empty($member['usergroup'])){
			$gid=intval($member['usergroup']);
			$group= M('AuthGroup')->token(false)->where(" id=$gid ")->find();
			if(!empty($group['id'])){
				if($feetype=='taskfee'){
					if($group['feetype']==1){
						//本组
						$taskfee=intval($group['taskfee'])/100;
						return $taskfee * $money;
						
					}elseif($group['feetype']==2){
						//分类
					}
				}elseif($feetype=='taskunionfee'){
					$taskfee=intval($group['taskunionfee'])/100;
					return $taskfee * $money;
				}elseif($feetype=='successunionfee'){
					$taskfee=intval($group['successunionfee'])/100;
					return $taskfee * $money;
				}
			}
		}
		return 0;
	}
	
	
	//任务支付-------------------------------------------------------------------------------------------------------------
	//创建支付-悬赏中标
	public function PayCreateTaskOrder($task=array(),$draft=array()){
		
		$id=intval($task['id']);
		$oid=intval($draft['oid']);
		if(!empty($draft['seller_uid']) && $id && $oid){
	
			$this->startTrans();
			//是否支付托管
			$istaskpay=$this->token(false)->lock(true)->where(" payin_uid=1 AND dataid=$id AND process=5 AND amount>0 ")->count();
			
			if($istaskpay){
				
				M('DataOrder')->startTrans();
			
				//悬赏				
				//检查中标金额
				$successmoney=M('DataOrder')->token(false)->lock(true)->where(" id=$id ")->sum('money');
				
				if($task['task_number']>1){
					
					$fee=$this->GetTaskFee($draft['seller_uid'],$task['money']);
					
					//计件悬赏
					if($successmoney < ($task['money']* $task['task_number'])){

						$post=array(
							'dataid'=>$task['id'],
							'subject'=>$task['id'].'号任务'.$draft['oid'].'号稿件中标', 
							'paytype'=>1, 
							'process'=>2, 
							'fee'=>$fee,
							'amount'=>$task['money']-$fee, //分
							'payin_uid'=>$draft['seller_uid'],  //收入用户UID
							'payin_username'=>$draft['seller_username']  //收入用户名
						);

						$cid=$this->AddConsume($post);
						if(!$this->SuccessConsume($cid)){
							$this->error=$this->getError();
							return false;
						}
						
						//中标推广
						$draftuid=intval($draft['seller_uid']);
						$member=M('Member')->token(false)->where(" uid=$draftuid ")->field('uid,username,unionid,uniontime,unionname')->find();

						if(time()<intval($member['uniontime']) && $member['unionid'] || intval($member['uniontime'])==0 && $member['unionid']){
							
							$fee=$this->GetTaskFee($member['unionid'],$task['money'],'successunionfee');

							if($fee){
								$post=array(
									'subject'=>$draft['oid'].'号中标推广 '.$member['username'],
									'dataid' =>$id,
									'amount' =>$fee,
									'unionuid'=>$member['unionid'],
									'payin_uid'=>$member['unionid'],
									'payin_username'=>$member['unionname'],
								);

								$cid=$this->AddConsume($post);
		
								if($cid){
									$this->SuccessConsume($cid);
								}
							}
						}
					

						M('DataOrder')->token(false)->lock(true)->where(" oid=$oid ")->save(array('process'=>1,'money'=>$task['money'],'verifytime'=>NowTime()));
						
						M('DataOrder')->commit();
						
						$this->commit();
						
						return array('cid'=>$cid);
					}else{
						$this->error='任务已没有名额!';
						return false;
					}
					
				}else{
					//单人悬赏
					//是否已支付托管
					$ispaytask=$this->token(false)->lock(true)->where(" payout_uid=1 AND dataid=$id ")->count();
					
					if(!$successmoney && !$ispaytask){
						//自动关闭时间
						if($task['task_mode']==2){
							$autoday=intval($draft['time']);
							$paymoney=intval($draft['offer'])*100;
						}else{
							$autoday=intval(C('task_auto_verifypay'));
							$paymoney=intval($task['money']);
						}

						$runtime=NowTime()+($autoday*24*60*60);
						
						$fee=$this->GetTaskFee($draft['seller_uid'],$paymoney);
						
						$post=array(
							'dataid'=>$task['id'],
							'subject'=>$task['id'].'号任务'.$draft['oid'].'号稿件中标', 
							'paytype'=>1, 
							'process'=>2, 
							'fee'=>$fee,
							'amount'=>$paymoney-$fee, //分
							'payin_uid'=>$draft['seller_uid'],  //收入用户UID
							'payin_username'=>$draft['seller_username'],  //收入用户名
							'autopay'=>1,
							'autopaytime'=>$runtime,
							'autocommand'=>1  //关闭任务退款雇主
						);

						$cid=$this->AddConsume($post);
						
						M('DataOrder')->token(false)->lock(true)->where(" oid=$oid ")->save(array('process'=>1,'money'=>$paymoney,'verifytime'=>NowTime()));
						
						M('DataOrder')->commit();
						
						$this->commit();
						
						return array('cid'=>$cid,'runtime'=>$runtime);
					}else{
						$this->error='任务已操作过了!';
						return false;
					}
				}
			
			}else{
				$this->error='任务未托管!';
				return false;
			}
			
		}else{
			$this->error='对不起!数据不存在!';
			return false;
		}
	}
	// 驳回交接原件
	public function RejectTaskOrder($task=array()){
		$id=intval($task['id']);
		$this->startTrans();
		//自动确认时间
		$autoday=intval(C('task_auto_verifypay'));

		$runtime=NowTime()+($autoday*24*60*60);
		$this->token(false)->lock(true)->where(" payout_uid=2 AND dataid=$id AND process=3 ")->save(array('process'=>2,'payin_uid'=>1,'newtime'=>NowTime(),'autopay'=>1,'autopaytime'=>$runtime,'autocommand'=>2));
		$this->commit();
		return $runtime;
	}
	
	//卖家交接原件 (单人悬赏-设置发货状态)
	public function PayDeliveryTaskOrder($task=array(),$draft=array()){
		
		$id=intval($task['id']);
		$oid=intval($draft['oid']);
		if(!empty($draft['seller_uid']) && $id && $oid){

			if($task['task_number']==1){
				
				$this->startTrans();
				//是否支付托管
				$istaskpay=$this->token(false)->lock(true)->where(" payin_uid=1 AND dataid=$id AND process=5 AND amount>0 ")->count();
				
				if($istaskpay){

					//是否已支付托管
					// $ispaytask=$this->token(false)->lock(true)->where(" payout_uid=1 AND dataid=$id AND process=2")->count();
					// $ispaytask=$this->token(false)->lock(true)->where("dataid=$id AND process=2")->count();
					// var_dump($id);
					// if($ispaytask){
						
						//自动确认时间
						$autoday=intval(C('task_auto_verifypay'));

						$runtime=NowTime()+($autoday*24*60*60);
					   
						$this->token(false)->lock(true)->where(" payout_uid=1 AND dataid=$id AND process=2 ")->save(array('process'=>3,'newtime'=>NowTime(),'autopay'=>1,'autopaytime'=>$runtime,'autocommand'=>2));
						
						$this->commit();

						return $runtime;

					// }else{
					// 	$this->error='任务没有权限!';
					// 	return false;
					// }
				
				}else{
					$this->error='任务未托管!';
					return false;
				}
			}else{
				$this->error='对不起!当前状态无法操作!';
				return false;
			}
		}else{
			$this->error='对不起!数据不存在!';
			return false;
		}
	}
	
	
	//任务退款并关闭
	public function TaskRefund($task=array()){
		$cid=intval($task['cid']);
		$id=intval($task['id']);
		
		if($cid && $id){
			//验证订单是否为支付
			$this->startTrans();
			$ispay=$this->token(false)->lock(true)->where(" id=$cid AND process=5")->count();
			if($ispay>0){
				//已托管过
				
				if($task['task_number']>1){
					//计件
					M('DataOrder')->startTrans();
					$successmoney=M('DataOrder')->token(false)->lock(true)->where(" id=$id AND process=1")->sum('money');
					
					$paymoney=$task['money'];
					if($successmoney){
						$paymoney=$task['money']-$successmoney;
					}
					
					M('DataOrder')->commit();
					
					$post=array(
						'subject'=>'系统退托管金'.$task['id'].'号任务', 
						'dataid' =>$task['id'],
						'amount' =>$paymoney,
						'payin_uid'=>$task['uid'],
						'payin_username'=>$task['username'],
					);
					
				}else{

					//悬赏
					$post=array(
						'subject'=>'系统退托管金'.$task['id'].'号任务', 
						'dataid' =>$task['id'],
						'amount' =>$task['money'],
						'payin_uid'=>$task['uid'],
						'payin_username'=>$task['username'],
					);

				}
				
						 
				if($newcid=$this->AddConsume($post)){
					//支付
					if($this->SuccessConsume($newcid)){
						
						M('Data')->where(" id='$id' ")->save(array('process_order'=>0,'process'=>9,'endtime'=>@time())); //关闭任务
						
						return true;
					}else{
						$this->error=$this->getError();
						return false;
					}
				}
					
			}
			
			$this->commit();
			
		}
		return false;
	}
	
	//设置退款金额
	public function SetReport($cid=0,$money=0){
		$id=intval($cid);
		$money=intval($money);
		$this->startTrans();
		if($this->token(false)->lock(true)->where(" id=$id AND process=3 AND amount>=$money ")->count()){
			$this->token(false)->lock(true)->where(" id=$id AND process=3 AND amount>=$money ")->save(array('newtime'=>NowTime(),'refundmoney'=>$money));
			$this->commit();
			return true;
		}
		$this->commit();
		return false;
	}
	
	//卖家确认支付 (设置确认付款状态)
	public function PaySuccessTaskOrder($task=array(),$draft=array()){
		$id=intval($task['id']);
		$oid=intval($draft['oid']);
		if(!empty($draft['seller_uid']) && $id && $oid){
			
			$this->startTrans();
			//是否已支付托管
			$consume=$this->token(false)->lock(true)->where(" payout_uid=1 AND dataid=$id AND process=3")->find();
			if(!empty($consume['id'])){
				if($this->SuccessConsume($consume['id'])){
					$this->commit();
					
					//任务推广(单人)
					if($task['task_number']==1){
						$taskuid=intval($task['uid']);
						$member=M('Member')->token(false)->where(" uid=$taskuid ")->field('uid,username,unionid,uniontime,unionname')->find();

						if(time()<intval($member['uniontime']) && $member['unionid'] || intval($member['uniontime'])==0 && $member['unionid']){
							
							$fee=$this->GetTaskFee($member['unionid'],$draft['money'],'taskunionfee');

							if($fee){
								$post=array(
									'subject'=>$id.'号任务推广,用户：'.$member['username'],
									'dataid' =>$id,
									'amount' =>$fee,
									'unionuid'=>$member['unionid'],
									'payin_uid'=>$member['unionid'],
									'payin_username'=>$member['unionname'],
								);

								$cid=$this->AddConsume($post);
		
								if($cid){
									$this->SuccessConsume($cid);
								}
							}
						}
					}
					
					//中标推广
					if($draft['money']){
						$draftuid=intval($draft['seller_uid']);
						$member=M('Member')->token(false)->where(" uid=$draftuid ")->field('uid,username,unionid,uniontime,unionname')->find();

						if(time()<intval($member['uniontime']) && $member['unionid'] || intval($member['uniontime'])==0 && $member['unionid']){
							
							$fee=$this->GetTaskFee($member['unionid'],$draft['money'],'successunionfee');

							if($fee){
								$post=array(
									'subject'=>$draft['oid'].'号中标推广 '.$member['username'],
									'dataid' =>$id,
									'amount' =>$fee,
									'unionuid'=>$member['unionid'],
									'payin_uid'=>$member['unionid'],
									'payin_username'=>$member['unionname'],
								);

								$cid=$this->AddConsume($post);
		
								if($cid){
									$this->SuccessConsume($cid);
								}
							}
						}
					}
					
					return true;
				}else{
					$this->error=$this->getError();
					$this->commit();
					return false;
				}
			}
			$this->commit();
			$this->error='对不起!当前状态无法操作!';
			return false;
		}else{
			$this->error='对不起!数据不存在!';
			return false;
		}
	}
	
	//交易获取列表
	
	//筛选-------------------------------
	public function GetMyConsume($orderarr=array(),$wherearr=array(),$order='id ASC',$showpage=10){
		$wheresql=$selectarray='';

		if(intval($_GET['search'])){
			
			$_GET['amount']=intval($_GET['amount'])*100;

			$wheresqlarr=SetWhere($_GET,$wherearr);

			$wheresql=$wheresqlarr[0];

			$selectarray=$wheresqlarr[1];

		}
		
		//排序-------------------------------
		$iforder=I('get.iforder',1,'int');

		if($iforder==1){
			$selectorder=' ASC';
			$iforder=2;
		}else{
			$selectorder=' DESC';
			$iforder=1;
		}
		
		$sqlorder=I('get.sqlorder',0,'int');
		foreach($orderarr as $key=>$value){
			if($sqlorder==$key){
				$order=$value['order'].$selectorder;
			}
		}
		
		$where=" payin_uid=$this->uid AND paytype<3 or paytype<3 AND payout_uid=$this->uid ";

		if($wheresql){
			$wheresql.=' AND '.$where.' AND '.$wheresql;
		}else{
			$wheresql=$where;
		}
		
		$execute='';
		if($selectarray){
			$execute=explode(',',implode(',',$selectarray).','.implode(',',$selectarray));
			$selectarray['amount']=$selectarray['amount']/100;
		}

		//数据-------------------------------
		$pagenum=I('get.p',0,'int');
		$list=$this->where($wheresql,$execute)->order($order)->page($pagenum,$showpage)->select();
		
		//页码-------------------------------
		$count=$this->where($wheresql,$execute)->count();
		$Page = new \Think\Page($count,$showpage);

		return array('list'=>$list,'page'=>$Page->show(),'count'=>$count,'orderarr'=>$orderarr,'iforder'=>$iforder,'sqlorder'=>$sqlorder,'pagenum'=>$pagenum,'selectarray'=>$selectarray);
	}
	
	//提现
	public function GetMyPayout($orderarr=array(),$wherearr=array(),$order='id ASC',$showpage=10){
		$wheresql=$selectarray='';
		
		//排序-------------------------------
		$iforder=I('get.iforder',1,'int');

		if($iforder==1){
			$selectorder=' ASC';
			$iforder=2;
		}else{
			$selectorder=' DESC';
			$iforder=1;
		}
		
		$sqlorder=I('get.sqlorder',0,'int');
		foreach($orderarr as $key=>$value){
			if($sqlorder==$key){
				$order=$value['order'].$selectorder;
			}
		}
		
		$wheresql=" payout_uid=$this->uid AND paytype=4 ";
		
		//数据-------------------------------
		$pagenum=I('get.p',0,'int');
		$list=$this->where($wheresql,$selectarray)->order($order)->page($pagenum,$showpage)->select();
		
		//页码-------------------------------
		$count=$this->where($wheresql,$selectarray)->count();
		$Page = new \Think\Page($count,$showpage);

		return array('list'=>$list,'page'=>$Page->show(),'count'=>$count,'orderarr'=>$orderarr,'iforder'=>$iforder,'sqlorder'=>$sqlorder,'pagenum'=>$pagenum,'selectarray'=>$selectarray);
	}
	
	//充值获取列表
	public function GetMyPayin($orderarr=array(),$wherearr=array(),$order='id ASC',$showpage=10){
		$wheresql=$selectarray='';
		
		//排序-------------------------------
		$iforder=I('get.iforder',1,'int');

		if($iforder==1){
			$selectorder=' ASC';
			$iforder=2;
		}else{
			$selectorder=' DESC';
			$iforder=1;
		}
		
		$sqlorder=I('get.sqlorder',0,'int');
		foreach($orderarr as $key=>$value){
			if($sqlorder==$key){
				$order=$value['order'].$selectorder;
			}
		}
		
		$wheresql=" payin_uid=$this->uid AND paytype=3 ";
		
		//数据-------------------------------
		$pagenum=I('get.p',0,'int');
		$list=$this->where($wheresql,$selectarray)->order($order)->page($pagenum,$showpage)->select();
		
		//页码-------------------------------
		$count=$this->where($wheresql,$selectarray)->count();
		$Page = new \Think\Page($count,$showpage);

		return array('list'=>$list,'page'=>$Page->show(),'count'=>$count,'orderarr'=>$orderarr,'iforder'=>$iforder,'sqlorder'=>$sqlorder,'pagenum'=>$pagenum,'selectarray'=>$selectarray);
	}
	
	//充值成功
	public function PayinSuccess($dingdan,$amount,$paytype){
		$this->startTrans();
		$amount=intval($amount);
		if(IsNum($dingdan) && $amount>0){	
			$consume=$this->token(false)->lock(true)->where(" serial='$dingdan' ")->find();
			if(!empty($consume['id']) && intval($consume['amount'])==$amount && intval($consume['process'])!=5 && $consume['bankcard']==$paytype){
				if($this->SuccessConsume($consume['id'])){
					$this->commit();
					return true;
				}else{
					$this->error=$this->getError();
					$this->commit();
					return false;
				}
			}
		}
		$this->error='对不起!数据不存在!';
		$this->commit();
		return false;
	}
	
	//提现
	public function Payout(){
		$money=intval($_POST['money']);
					   
		$withdrawsmall=intval(C('withdrawsmall'));
					   
		$withdrawbig=intval(C('withdrawbig'));
		
		$member= M('Member')->token(false)->where(" uid=$this->uid ")->field('uid,username,bankcard,paysecurity')->find();
		$bankcard=$member['bankcard'];
		
		if(!$bankcard){
			$this->error='对不起！请填写提现支付宝帐号！<a href="/member/bankcard/index">[点击填写]</a>';
			return false;
		}
		
		if($money<$withdrawsmall){
			$this->error='对不起！提现金额不能小'.$withdrawsmall.'元！';
			return false;
		}
		
		if($money>$withdrawbig){
			$this->error='对不起！最大提现金额为'.$withdrawbig.'元！';
			return false;
		}
		
		if(!$this->CheckUserMoney($this->uid,$money)){
			$this->error='对不起！您的可用余额不足'.$money.'元不能提现！';
			return false;
		}
		
		$withdrawnum=intval(C('withdrawnum'));
		$count=$this->token(false)->where(" payout_uid=$this->uid AND paytype=4 AND FROM_UNIXTIME(dateline,'%Y-%m-%d')=curdate() ")->group("curdate()")->count();
		if($count>=$withdrawnum){
			$this->error='对不起！您今日已提现'.$count.'次，明日再来吧！';
			return false;
		}
		
		//手机安全
		$loginsecurity=new \Login\Model\MemberModel();
		$security=$loginsecurity->MobileSecurity($member['uid'],$member,'paysecurity');
		if(!$security){
			$this->callback='$("#MobileCode").show(500);$("#ShowSecCode").hide();$("#MobileCodeHelp").html("'.$loginsecurity->getError().'").show();';
			return false;
		}
		
		$post=array(
			'subject'=>'提现',
			'bankcard'=>$bankcard,
			'paytype' =>4,
			'amount' =>$money*100,
			'status' =>1,
			'payout_uid'=>$this->uid,
			'fee'=>floatval(C('withdrawfee'))*$money*100, 
			'payout_username'=>$this->username,
		);

		$cid=$this->AddConsume($post);

		if($cid){
			if($this->SuccessConsume($cid)){
				return true;
			}else{
				$this->error=$this->getError();
				return false;
			}
		}
		return false;			   
	}
	
	//充值
	public function Payin(){
		$id=intval($_GET['id']);
		if($id){
			$consume=$this->token(false)->where(" payin_uid=$this->uid AND id=$id AND paytype=3 AND process!=5 ")->find();
			if(!empty($consume['id'])){
				if($consume['bankcard']=='alipay'){
					return $this->AlipayPay($consume['amount']/100,$consume['serial']);
				}elseif($consume['bankcard']=='tenpay'){
					return $this->TenpayPay($consume['amount'],$consume['serial']);
				}
			}
			$this->error='对不起!数据不存在!';
			return false;
				
		}else{
			$money=intval($_POST['money']);
			$timearr=@gettimeofday();
			$payorder=@date('YmdHis',$timearr['sec']).intval(substr($timearr['usec'],0,4));
				
			//支付宝
			if(intval($_POST['type'])==1){
	
				if($this->PayinLog($money,$payorder)){
					return $this->AlipayPay($money,$payorder);
				}
				
				$this->error='对不起!您未充值记录太多!';
				return false;
				
			}elseif(intval($_POST['type'])==2){ //财付通
				$payorder=iconv_substr($payorder,8,20,C('S_CHARSET'));
				if($this->PayinLog($money,$payorder)){
					return $this->TenpayPay($money,$payorder);
				}
				
				$this->error='对不起!您未充值记录太多!';
				return false;
			}
		}
	}
	
	//充值记录
	public function PayinLog($money,$payorder){
		$this->startTrans();
		//记录最多5条未充值支付
		if($this->token(false)->lock(true)->where(" payin_uid=$this->uid AND paytype=3 AND process!=5 ")->count()>=5){
			$this->error='对不起!您未充值记录太多!';
			$this->commit();
			return false;
		}
		
		if($_POST['type']==1){
			$subject='支付宝充值';
			$bankcard='alipay';
		}elseif($_POST['type']==2){
			$subject='财付通充值';
			$bankcard='tenpay';
		}
		
		$post=array(
			'subject'=>$subject,
			'amount' =>$money*100,
			'serial' =>$payorder,
			'paytype'=>3,
			'bankcard'=>$bankcard,
			'payin_uid'=>$this->uid,
			'payin_username'=>$this->username,
		);

		$cid=$this->AddConsume($post);
		
		if ($cid){
			$this->commit();
			return $cid;
		}
		
		$this->commit();
		$this->error=$this->getError();
		
		return false;
	}
	
	//财付通
	public function TenpayPay($money=0,$payorder=0){
		
		require_once (FOXPHP_PATH.'/Apps/Consume/Class/PayRequestHandler.class.php');
	
		/* 商户号 */
		$bargainor_id =C('tenpayid');
		
		/* 密钥 */
		$key = C('tenpaykey');
		
		/* 返回处理地址 */
		//$return_url = C('S_URL').'/api/tenpay/callback.php';
		$return_url = C('S_URL').'/api/tenpay/callback';
		
		$sp_billno=$payorder;
		
		/* 财付通交易单号，规则为：10位商户号+8位时间（YYYYmmdd)+10位流水号 */
		$transaction_id = $bargainor_id .$payorder;
		
		/* 创建支付请求对象 */
		$reqHandler = new \PayRequestHandler();
		$reqHandler->init();
		$reqHandler->setKey($key);
		
		//----------------------------------------
		//设置支付参数
		//----------------------------------------
		$reqHandler->setParameter("bargainor_id", $bargainor_id);			//商户号
		$reqHandler->setParameter("sp_billno", $sp_billno);					//商户订单号
		$reqHandler->setParameter("transaction_id", $transaction_id);		//财付通交易单号
		$reqHandler->setParameter("total_fee", $money *100);					//商品总金额,以分为单位
		$reqHandler->setParameter("return_url", $return_url);				//返回处理地址
		$reqHandler->setParameter("desc", C('paygoodsname'));	//商品名称
		$reqHandler->setParameter("bank_type",intval($_POST['bank']));	//银行ID
		
		//用户ip,测试环境时不要加这个ip参数，正式环境再加此参数
		$reqHandler->setParameter("spbill_create_ip", $_SERVER['REMOTE_ADDR']);
		
		//请求的URL
		$reqUrl = $reqHandler->getRequestURL();
		
		//debug信息
		//$debugInfo = $reqHandler->getDebugInfo();
		
		//echo "<br/>" . $reqUrl . "<br/>";
		//echo "<br/>" . $debugInfo . "<br/>";
		
		//重定向到财付通支付
		$reqHandler->doSend();
	}
	
	//支付宝
	public function AlipayPay($money=0,$payorder=0){

		require_once(FOXPHP_PATH.'/Apps/Consume/Class/alipay_config.php');

		require_once(FOXPHP_PATH.'/Apps/Consume/Class/alipay_service.php');
		
		//必填参数
		$out_trade_no = $payorder;		//请与贵网站订单系统中的唯一订单号匹配
		$subject      = C('paygoodsname');	//订单名称，显示在支付宝收银台里的“商品名称”里，显示在支付宝的交易管理的“商品名称”的列表里。
		$body         = C('paydescription');	//订单描述、订单详细、订单备注，显示在支付宝收银台里的“商品描述”里
		$total_fee    = $money;	//订单总金额，显示在支付宝收银台里的“应付总额”里

		//扩展功能参数——网银提前
		$pay_mode	  = 'bankPay';
		$defaultbank =$_POST['bank'];

		if ($pay_mode == "directPay") {
		  $paymethod    = "directPay";	//默认支付方式，四个值可选：bankPay(网银); cartoon(卡通); directPay(余额); CASH(网点支付)
		  $defaultbank  = "";
		}else {
		  $paymethod    = "bankPay";		//默认支付方式，四个值可选：bankPay(网银); cartoon(卡通); directPay(余额); CASH(网点支付)
		  $defaultbank  = $defaultbank;		//默认网银代号，代号列表见http://club.alipay.com/read.php?tid=8681379
		}

		//扩展功能参数——防钓鱼
		$encrypt_key  = '';					//防钓鱼时间戳，初始值
		$exter_invoke_ip = '';				//客户端的IP地址，初始值
		if($antiphishing == 1){
		  $encrypt_key = query_timestamp($partner);
		  $exter_invoke_ip = '';			//获取客户端的IP地址，建议：编写获取客户端IP地址的程序
		}

		//扩展功能参数——其他
		$extra_common_param = '';			//自定义参数，可存放任何内容（除=、&等特殊字符外），不会显示在页面上
		$buyer_email		= '';			//默认买家支付宝账号

		//扩展功能参数——分润(若要使用，请按照注释要求的格式赋值)
		$royalty_type		= "";			//提成类型，该值为固定值：10，不需要修改
		$royalty_parameters	= "";
		//提成信息集，与需要结合商户网站自身情况动态获取每笔交易的各分润收款账号、各分润金额、各分润说明。最多只能设置10条
		//各分润金额的总和须小于等于total_fee
		//提成信息集格式为：收款方Email_1^金额1^备注1|收款方Email_2^金额2^备注2
		//如：
		//royalty_type = "10"
		//royalty_parameters	= "111@126.com^0.01^分润备注一|222@126.com^0.01^分润备注二"


		//扩展功能参数——自定义超时(若要使用，请按照注释要求的格式赋值)
		//该功能默认不开通，
		//申请开通方式：拨打0571-88158090申请或提交集成申请（https://b.alipay.com/support/helperApply.htm?action=consultationApply）
		//超时时间，不填默认是15天。设置范围：1m~15d。 m-分钟，h-小时，d-天，1c-当天（无论何时创建，交易都在0点关闭）
		$it_b_pay			= "";

		/////////////////////////////////////////////////

		//构造要请求的参数数组，无需改动
		$parameter = array(
			  "service"			=> 'create_direct_pay_by_user',	//接口名称，不需要修改
			  "payment_type"		=> "1",               			//交易类型，不需要修改

			  //获取配置文件(alipay_config.php)中的值
			  "partner"			=> $partner,
			  "seller_email"		=> $seller_email,
			  "return_url"		=> $return_url,
			  "notify_url"		=> $notify_url,
			  "_input_charset"	=> $_input_charset,
			  "show_url"			=> $show_url,

			  //从订单数据中动态获取到的必填参数
			  "out_trade_no"		=> $out_trade_no,
			  "subject"			=> $subject,
			  "body"				=> $body,
			  "total_fee"			=> $total_fee,

			  //扩展功能参数——网银提前
			  "paymethod"			=> $paymethod,
			  "defaultbank"		=> $defaultbank,

			  //扩展功能参数——防钓鱼
			  "anti_phishing_key"	=> $encrypt_key,
			  "exter_invoke_ip"	=> $exter_invoke_ip,

			  //扩展功能参数——自定义参数
			  "buyer_email"		=> $buyer_email,
			  "extra_common_param"=> $extra_common_param,
			  
			  //扩展功能参数——分润
			  "royalty_type"		=> $royalty_type,
			  "royalty_parameters"=> $royalty_parameters,

			  //扩展功能参数——自定义超时
			  "it_b_pay"			=> $it_b_pay
		);

		//构造请求函数
		$alipay = new \alipay_service($parameter,$key,$sign_type);
		return $alipay->build_form();
	}
	
	//升级VIP  会员信息 | 用户组ID | 购买时间 | 购买金额
	public function PayVip($member=array(),$id=0,$buyviptime=0,$buyvipmoney=0){
		$id=intval($id);
		$buyviptime=intval($buyviptime)*24*60*60;
		$buyvipmoney=intval($buyvipmoney);
		
		$group=M('AuthGroup')->token(false)->where(" id=$id ")->find();
		
		if($member['uid'] && $group['id'] && $buyviptime && $buyvipmoney){
			
			if(!$this->CheckUserMoney($this->uid,$buyvipmoney*100)){
				$this->error='对不起！您的可用余额不足'.$buyvipmoney.'元不能购买！请充值后操作！';
				return false;
			}
			
			$post=array(
				'subject'=>$this->username.'(UID '.$this->uid.')购买VIP',
				'amount' =>$buyvipmoney*100,
				'payout_uid'=>$this->uid,
				'payout_username'=>$this->username,
			);

			$cid=$this->AddConsume($post);

			if($cid){
				//支付
				if(!$this->SuccessConsume($cid)){
					$this->error=$this->getError();
					return false;
				}
				
				if(intval($member['vipendtime'])>0){
					$vipendtime=$member['vipendtime']+$buyviptime;
				}else{
					$vipendtime=time()+$buyviptime;
				}
				
				M('Member')->token(false)->where(" uid=$this->uid ")->save(array('isvip'=>1,'usergroup'=>$id,'vipendtime'=>$vipendtime,'groupname'=>$group['title']));
				
				return true;
			}
				
			return false;
			
		}else{
			$this->error='数据不存在!';
			return false;
		}
	}
	
	//所有交易金额
	public function GetTransactionMoney($payinuid=0){
		$payinuid=intval($payinuid);
		return intval($this->token(false)->where(" payin_uid=$payinuid AND process=5 AND paytype<3 ")->sum('amount'))/100;
	}
}

?>